<template>
    <div>
      <a-modal
        :title="title"
        :visible="visible"
        class="large-modal"
        @ok="handleOk"
        ok-text="选中提交"
        @cancel="$emit('update:visible',false)"
      >
        <a-row v-loading="loading">
          <a-col :span="6">
            <a-tree
              style="height: 400px; overflow: auto"
              :selected-keys.sync="selectedKeys"
              :replace-fields="replaceFields"
              :tree-data="orgTreeData"
              @select="getOrgPerson"
            />
          </a-col>
          <a-col :span="1" />
          <a-col :span="17">
            <a-row>
              <a-col
                :span="24"
                class="mb20p flex align-items-center"
              >
                <a-input
                  v-model.trim="likeSearch"
                  placeholder="员工名称/电话号码/员工编号"
                />
                <a-button
                  type="primary"
                  class="ml20p"
                  @click="onSearch"
                >搜索</a-button>
                <a-button
                  class="ml20p"
                  @click="likeSearch = '';onSearch()"
                >重置</a-button>
              </a-col>
            </a-row>
            <!-- <a-row>
              <a-tag
                v-for="(item,index) of selectedRows"
                :key="item.id"
                class="mb20p"
                :closable="selectedRows.length>1?true:false"
                @close="removePerson($event,index)"
              >
                {{ item.employeeName }}
              </a-tag>
            </a-row> -->
            <a-row>
              <a-tag
                v-for="(item,index) of personList"
                :key="item.id"
                class="mb20p"
                :closable="personList.length>1?true:false"
                @close="removePerson($event,index,item)"
              >
                {{ item.employeeName }}
              </a-tag>
            </a-row>
            <!-- @select-click="(e) => (this.selectedRows = e.rows)" -->
            <b-table
              ref="table"
              :columns="columns"
              :select-config="{use : mode !== 'multiple', type: 'checkbox', rowKey: 'userId'}"
              :scroll="{ y: 260 }"
              :request="loadData"
              :page-keys="['pageNumber', 'pageSize','totalSize']"
              :out-selected-row-keys="selectedRowKeys"
              :row-selection="rowSelection"
               row-key="id"
            >
              <template
                v-if="mode === 'multiple'"
                slot="action"
                slot-scope="text, record"
              >
                <a @click="option(record)">{{ optionText(record) }}</a>
              </template>
            </b-table>
          </a-col>
        </a-row>
      </a-modal>
    </div>
  </template>
  
  <script>
  import { getCustOrgTree, getStaff } from '@/api/subassembly/TreeSelectOrganization'
  import {  getEmployeeList } from '@/api/science'
  
  export default {
    props: {
      list: {
        type: Array,
        default: () => []
      },
      visible: {
        type: Boolean,
        required: true
      },
      title: {
        type: String,
        default: () => '添加参与人'
      },
      mode: {
        type: String,
        default: ''
      },
      showAdd: {
        type: Boolean,
        default: () => false
      },
      orgQuery: {
        type: Object,
        default: () => null
      },
      orgId: {
        type: String,
        default: () => ''
        // default: () => '06bcbdacb4374523bdaf66586c45f749'
      },
      needData: {
        type: Boolean,
        default: () => true
      },
      maxSelectLength: {
        type: Number,
        default: () => null
      },
      //主键
      primaryKey: {
        type: String,
        default: 'id'
      }
    },
    data() {
      return {
        columns: [
          {
            title: '员工名称',
            dataIndex: 'employeeName'
          },
          {
            title: '员工编号',
            dataIndex: 'employeeNo'
          },
          {
            title: '电话号码',
            dataIndex: 'phone'
          },
          {
            title: '岗位',
            dataIndex: 'post'
          },
        //   {
        //     title: '操作',
        //     width: '100px',
        //     scopedSlots: { customRender: 'action' }
        //   }
        ],
        queryParam: {},
        loadData: async (params) => {
          if (!this.selectedKeys.length) {
            return { code: 200, data: [] }
          }
          let args = Object.assign(params, this.queryParam)
          args.subItemId = this.selectedKeys[0]
          args.pageNo = args.pageNumber
          args.queryPostRelation = true
          let res = await getEmployeeList(args)
          setTimeout(() => {
            let tableData = []
          this.$refs.table.tableData.forEach((item,index) => {
            this.personList.forEach(sub => {
              if (item.id === sub.id) {
                tableData.push(item)
                this.selectedRowKeys.push(item.id)
              }
            })
          })
          // this.selectedRows = this.$clone(this.list)
          console.log('tableDatatableDatatableData',tableData)
          this.selectedRows = this.$clone(tableData)
          this.difflist = []
          if(tableData.length>0){  
            this.difflist = this.personList.filter(item1 => tableData.findIndex(item2 => item2.id === item1.id) === -1);
          }else{
            this.difflist = [...this.personList]
          }
          console.log(this.difflist,'this.difflist')
          }, 1000);
          return { ...res, data: res.data }
          
        },
        isAdd: true,
        likeSearch: undefined,
        loading: false,
  
        selectedKeys: [],
        orgTreeData: [],
        replaceFields: {
          children: 'children',
          title: 'label',
          key: 'id'
        },
        selectPersons: [],
        selectedRowKeys: [],
        selectedRows: [],
        personList:this.list,//已有人员数组
        difflist:[],
      }
    },
    computed: {
      rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          this.personList = [...selectedRows,...this.difflist]
        }
      }
    }
    },
    created() {},
    watch: {
      async visible(val) {
        if (val) {
          console.log('this.list',this.list)
          // this.selectedRowKeys = this.list.map((v) => v.id)
          this.loading = true
          let res = await getCustOrgTree(
            this.orgQuery
              ? this.orgQuery
              : {
                  baseOrgType: 0, // 是否基础组织 0否 1是
                  containVirtual: 0 //是否包含虚拟组织 0包含 1 不包含
                }
          )
          this.loading = false
        
          if (res.data && res.data.length > 0) {
            this.orgTreeData = res.data
            if (this.orgId) {
              this.recursion(this.orgTreeData, null)
            }
            this.selectedKeys = [this.orgTreeData[0].id]
            this.$refs.table.getData(null, true)
          }
        } else {
          this.selectedRows = []
          this.queryParam = {}
          this.likeSearch = ''
        }
      }
    },
    methods: {

      recursion(items, parent) {
        for (let i = 0; i < items.length; i++) {
          let item = items[i]
          if (item.id === this.orgId) {
            this.orgTreeData = [item]
          } else {
            if (item.children) {
              this.recursion(item.children, item)
            }
          }
        }
      },
      removePerson(e, index,item) {
        e && e.preventDefault()
        this.selectedRows= this.selectedRows.filter(i => i.id !== item.id)
        this.selectedRowKeys = this.selectedRowKeys.filter(i => i !== item.id)
        this.personList= this.personList.filter(i => i.id !== item.id)
        this.$forceUpdate()
      },
      optionText(record) {
        let res = this.selectPersons.find((v) => v[this.primaryKey] === record[this.primaryKey])
        return res ? '删除' : '添加'
      },
      option(record) {
        if (this.mode !== 'multiple') {
          this.selectPersons = []
        }
        let resIndex = this.selectPersons.findIndex((v)=> v[this.primaryKey] === record[this.primaryKey])
        if (resIndex !== -1) {
          this.removePerson(null, resIndex)
        } else {
          this.selectPersons.push(record)
        }
      },
      handleOk(e) {
        if (this.mode !== 'single' && this.maxSelectLength !== null) {
          if (this.personList.length > this.maxSelectLength) {
            return this.$noticeWarning(`最多可选中${this.maxSelectLength}人`)
          }
        }
        this.personList.map((v) => { 
          v.orgId = this.selectedKeys[0]
        })
        this.personList =  this.personList.map(v=>{
          v.name = v.employeeName;
          return v
        })
        this.$emit('update:visible', false)
        this.$emit('update:completeEmployeeInside', this.personList)
        this.$emit('getSelectPerson', this.personList)
      },
      getOrgPerson(selectedKeys, info) {
        this.selectedKeys = selectedKeys
        this.onSearch()
      },
      getOutside() {},
      onSearch() {
        this.queryParam.key = this.likeSearch
        this.$refs.table.getData(null, true)
      }
    }
  }
  </script>
  
  <style lang="less" scoped>
  </style>
  